package org.softmed.rest.server.xstream;

import java.net.URLEncoder;

import org.softmed.persistence.PersistenceManager;
import org.softmed.rest.config.Application;
import org.softmed.rest.generation.xml.PagedList;
import org.softmed.rest.generation.xml.XMLMarshaller;

public class PagedListConverter implements XMLMarshaller {

	public String toXML(Object obj, PersistenceManager odbUtil,
			Application app, Object... options) throws Throwable {

		PagedList list = (PagedList) obj;

		if (list == null || list.getItems() == null
				|| list.getItems().size() == 0) {
			return "<paged-list item-count=\"0\" items-per-page=\""
					+ list.getCurrentItemsPerPage() + "\"/>\n";
		}

		String xml = "<paged-list page=\"" + list.getCurrentPageNumber()
				+ "\" item-count=\"" + list.getItemCount()
				+ "\" items-per-page=\"" + list.getCurrentItemsPerPage()
				+ "\" ";

		if (list.getPreviousPageURI() != null)
			xml += " previous=\"" + encodeAmpersand(list.getPreviousPageURI())
					+ "\"";

		if (list.getNextPageURI() != null)
			xml += " next=\"" + encodeAmpersand(list.getNextPageURI()) + "\"";

		if (list.getFirstPageURI() != null)
			xml += " first=\"" + encodeAmpersand(list.getFirstPageURI()) + "\"";

		if (list.getLastPageURI() != null)
			xml += " last=\"" + encodeAmpersand(list.getLastPageURI()) + "\"";

		xml += ">\n";

		XMLMarshaller listItemMarshaller = null;
		if (options != null && options.length > 0) {
			String detail = (String) options[0];
			if (detail.equals("detailed")) {
				// buggy
				DefaultToXMLHideNonNativeConverter conv = XMLCache
						.getNormalConverter(list.getItems().get(0).getClass(),
								odbUtil, app, options);

				// DefaultToXMLHideNonNativeConverter conv = new
				// DefaultToXMLHideNonNativeConverter();
				conv.setDetailed();
				listItemMarshaller = conv;
			}
		} else
			listItemMarshaller = new ListItemToXML();

		// ListItemToXML specific = new ListItemToXML();
		URIXMLEditor uriXmlEditor = new URIXMLEditor();
		String temp = null;

		for (Object object : list.getItems()) {
			temp = listItemMarshaller.toXML(object, odbUtil, app, options);
			temp = uriXmlEditor.setURI(odbUtil, object, temp, app);
			xml += temp + "\n";
		}

		xml += "</paged-list>";
		return xml;

	}

	public String encodeAmpersand(String url) {
		return url.replaceAll("&", "&amp;");
	}

	public PagedListConverter clone() {
		return new PagedListConverter();
	}

}
